package org.vdab.projects.tasks.client.gui;

import org.vdab.projects.tasks.client.dal.GWTEntityManager;
import org.vdab.projects.tasks.client.entities.ClientTaskBook;
import org.vdab.projects.tasks.client.gui.widgets.EntityListBoxWidget;
import org.vdab.projects.tasks.client.util.DelayedList;
import org.vdab.projects.tasks.client.util.ICommand;
import org.vdab.projects.tasks.client.util.MessageGuard;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class TaskBookSelector extends Composite {

	private static TaskBookSelectorUiBinder uiBinder = GWT
			.create(TaskBookSelectorUiBinder.class);

	interface TaskBookSelectorUiBinder extends
			UiBinder<Widget, TaskBookSelector> {
	}

//	public TaskBookSelector() {
//		initWidget(uiBinder.createAndBindUi(this));
//	}

	private GWTEntityManager em;
	
	private DelayedList<ClientTaskBook> ctbList = new DelayedList<ClientTaskBook>();
	
	@UiField(provided=true)
	EntityListBoxWidget<ClientTaskBook> lbTaskbooks;

	
	@UiField 
	TaskBookWidget taskBookWidget;

	public TaskBookSelector(GWTEntityManager em) throws Exception {
		MessageGuard.Log("in TaskBookSelector ctr");
		lbTaskbooks = new EntityListBoxWidget<ClientTaskBook>(ctbList);						
		MessageGuard.Log("in TaskBookSelector ctr, after creation of EntityListBox (lbTaskbooks)");
		initWidget(uiBinder.createAndBindUi(this));		

		this.em = em;		
		
		MessageGuard.Log("in TaskBookSelector ctr, at end");
	}
	
	
	public TaskBookSelector init() throws Exception{
		MessageGuard.Log("in TaskBookSelector.init()");
		
		ctbList.setOnFirstEntityAdded(new ICommand<ClientTaskBook>() {			
			@Override
			public void execute(ClientTaskBook entity) throws Exception {
				taskBookWidget.set(entity);
			}
		});
		
		em.getTaskBooks(ctbList);		
		return this;
	}

	@UiHandler("btnAdd")
	void onClick(ClickEvent e) {
		try {
			this.ctbList.addEntity(em.createNewTaskBook());
		} catch (Exception ex) {
			MessageGuard.Log(ex.getLocalizedMessage());
		}
	}
	
	@UiHandler("lbTaskbooks")
	void onChanged(ChangeEvent e){
		try {
			this.taskBookWidget.set(lbTaskbooks.getSelectedEntity());			
		} catch (Exception ex) {
			MessageGuard.Log(ex.getLocalizedMessage());
		}
	}
}
